import {ref, computed} from 'vue'
import {NCard, NScrollbar, NList, NListItem, NEmpty, NButton, NTag, NSpace, NTabs, NTabPane, NThing, NInputNumber, NStatistic} from 'naive-ui'
import {useXianLuStore} from '#imports'
import {LazyIcon} from '#components'

export interface ShangdianProps {
    value: boolean;
}

export default defineNuxtComponent({
    name: '商店组件',
    props: {
        value: {
            type: Boolean,
            default: false
        }
    },
    emits: ['update:value'],
    setup(props: ShangdianProps, {emit,}) {
        const store = useXianLuStore()
        const activeTab = ref('seeds')

        // 计算用户拥有的灵石数量
        const lingshiAmount = computed(() => {
            const lingshiItem = store.itemList.find(item => item.type === 'lingshi')
            return lingshiItem ? lingshiItem.amount : 0
        })

        // 模拟商店物品数据
        const shopItems = ref([
            {
                id: 'seed1',
                type: 'seeds',
                name: '灵草种子',
                price: 50,
                description: '基础灵草种子，可种植获得灵草',
                icon: '🌱'
            },
            {
                id: 'seed2',
                type: 'seeds',
                name: '灵花种子',
                price: 100,
                description: '基础灵花种子，可种植获得灵花',
                icon: '🌷'
            },
            {
                id: 'seed3',
                type: 'seeds',
                name: '灵果种子',
                price: 150,
                description: '基础灵果种子，可种植获得灵果',
                icon: '🍎'
            },
            {
                id: 'tool1',
                type: 'tools',
                name: '灵锄',
                price: 200,
                description: '基础灵锄，可提高种植效率',
                icon: '⛏️'
            },
            {
                id: 'tool2',
                type: 'tools',
                name: '灵镰',
                price: 250,
                description: '基础灵镰，可提高收获效率',
                icon: '🔪'
            },
            {
                id: 'material1',
                type: 'materials',
                name: '灵铁',
                price: 300,
                description: '基础炼器材料',
                icon: '🔧'
            },
            {
                id: 'material2',
                type: 'materials',
                name: '灵铜',
                price: 350,
                description: '基础炼器材料',
                icon: '🔨'
            }
        ])

        // 购买数量
        const purchaseQuantity = ref<Record<string, number>>({})

        // 初始化购买数量
        shopItems.value.forEach(item => {
            purchaseQuantity.value[item.id] = 1
        })

        // 根据标签筛选物品
        const filteredItems = computed(() => {
            if (activeTab.value === 'all') {
                return shopItems.value
            } else {
                return shopItems.value.filter(item => item.type === activeTab.value)
            }
        })

        // 获取所有物品类型
        const itemTypes = computed(() => {
            const types = new Set<string>()
            shopItems.value.forEach(item => types.add(item.type))
            return Array.from(types)
        })

        // 根据物品类型获取标签名称
        const getTypeName = (type: string) => {
            switch (type) {
                case 'seeds':
                    return '种子'
                case 'tools':
                    return '工具'
                case 'materials':
                    return '材料'
                default:
                    return type
            }
        }

        // 购买物品
        const purchaseItem = (item: any) => {
            const quantity = purchaseQuantity.value[item.id] || 1
            const totalPrice = item.price * quantity

            // 检查用户灵石是否足够
            const lingshiItem = store.itemList.find(i => i.type === 'lingshi')
            if (!lingshiItem || lingshiItem.amount < totalPrice) {
                // 灵石不足，显示提示（这里可以添加提示逻辑）
                alert('灵石不足！')
                return
            }

            // 扣除灵石
            lingshiItem.amount -= totalPrice

            // 添加物品到背包
            store.addItem({
                type: item.type,
                name: item.name,
                amount: quantity,
                description: item.description
            })
        }

        const handleClose = () => {
            emit('update:value', false)
        }

        return () => (
            <div style={{
                display: props.value ? 'block' : 'none',
                position: 'fixed',
                right: '20px',
                bottom: '20px',
                width: '600px',
                height: '80%',
                zIndex: 1000,
                boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
                borderRadius: '8px',
                overflow: 'hidden'
            }}>
                <NCard title="商店" bordered={false} style={{height: '100%'}}>
                    {{
                        "header-extra": () => <NButton onClick={handleClose} circle={true} quaternary={true}>
                            <LazyIcon name={"ant-design:close-outlined"} size={"16"}/>
                        </NButton>,
                        action: () => <NSpace justify={"end"}>
                            <NButton size={"small"} onClick={handleClose}>关闭</NButton>
                        </NSpace>,
                        default: () => (
                            <div>
                                {/* 顶部显示灵石数量 */}
                                <div style={{
                                    padding: '10px',
                                    marginBottom: '10px',
                                    background: '#f5f5f5',
                                    borderRadius: '4px',
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'center'
                                }}>
                                    <NStatistic label="灵石数量" value={lingshiAmount.value}>
                                        {{
                                            prefix: () => <span style={{marginRight: '4px'}}>💎</span>
                                        }}
                                    </NStatistic>
                                </div>
                                
                                <NTabs value={activeTab.value}
                                       onUpdateValue={(value) => activeTab.value = value}>
                                    <NTabPane name="all" tab="全部">
                                        <NScrollbar style={{maxHeight: 'calc(100% - 80px)'}}>
                                            {renderItemList()}
                                        </NScrollbar>
                                    </NTabPane>

                                    {itemTypes.value.map(type => (
                                        <NTabPane key={type} name={type} tab={getTypeName(type)}>
                                            <NScrollbar style={{maxHeight: 'calc(100% - 80px)'}}>
                                                {renderItemList()}
                                            </NScrollbar>
                                        </NTabPane>
                                    ))}
                                </NTabs>
                            </div>
                        )
                    }}
                </NCard>
            </div>
        )

        // 渲染物品列表
        function renderItemList() {
            return filteredItems.value.length > 0 ? (
                <NList bordered={false}>
                    {filteredItems.value.map((item, index) => (
                        <NListItem key={index}>
                            <NThing title={item.name} description={item.description}>
                                {{
                                    avatar: () => <div class="text-2xl">{item.icon}</div>,
                                    default: () => (
                                        <div>
                                            <div class="mb-2">
                                                <NTag type="success">价格: {item.price} 灵石</NTag>
                                            </div>
                                            <NSpace>
                                                <NInputNumber
                                                    v-model:value={purchaseQuantity.value[item.id]}
                                                    min={1}
                                                    max={99}
                                                    style="width: 100px"
                                                />
                                                <NButton
                                                    type="primary"
                                                    onClick={() => purchaseItem(item)}
                                                >
                                                    购买
                                                </NButton>
                                            </NSpace>
                                        </div>
                                    )
                                }}
                            </NThing>
                        </NListItem>
                    ))}
                </NList>
            ) : (
                <NEmpty description="没有找到物品"/>
            )
        }
    }
})